cc.Class({
  extends: cc.Component,

  properties: {
    camera: {
      type: cc.Camera,
      default: null,
    },
    shake: 0,   //持续抖动的时长
    shakeAmount: 0.7,   //振幅越大抖动越厉害
    decreaseFactor: 1.0,  // 抖动幅度（振幅),
    shakeRandomAmount: 30,  //抖动随机幅度
  },

  ctor() {
    this._shakeOffset = cc.v2(0, 0);
  },

  onEnable() {
    cc.CEventManager.instance.registerEvent(EVENTS.SMALL_CAMERA_SHAKE, this, 0, "smallCameraShake");
    cc.CEventManager.instance.registerEvent(EVENTS.BIG_CAMERA_SHAKE, this, 0, "bigCameraShake");

  },

  onDisable() {
    cc.CEventManager.instance.releaseAllEvents(this);

  },

  smallCameraShake() {
    this.shakeAmount = Math.max(this.shakeAmount, 0.25);
    this.shake = Math.max(this.shake, 0.3);
    this.enabled = true;
  },

  bigCameraShake() {
    this.shakeAmount = Math.max(this.shakeAmount, 0.5);
    this.shake = Math.max(this.shake, 0.5);
    this.enabled = true;
  },

  update(dt) {
    if (this.camera) {
      this.updateShake(dt);
      let pos = this.node.convertToWorldSpaceAR(cc.Vec2.ZERO);
      pos = this.camera.node.parent.convertToNodeSpaceAR(pos);
      pos.addSelf(this._shakeOffset);
      this.camera.node.position = pos;
    }
  },

  updateShake(dt) {
    if (this.shake > 0) {
      this._shakeOffset.x = (-0.5 + Math.random()) * this.shakeRandomAmount / this.camera.zoomRatio;
      this._shakeOffset.y = (-0.5 + Math.random()) * this.shakeRandomAmount / this.camera.zoomRatio;
      this._shakeOffset.mulSelf(this.shakeAmount);
      this.shake -= dt * this.decreaseFactor;
    } else {
      this.shake = 0;
      this._shakeOffset.x = 0;
      this._shakeOffset.y = 0;
    }
  },

});
